/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

//import static com.google.android.tv.settings.TvSettings.System.SCREEN_DIM_TIMEOUT;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.provider.Settings;
import android.preference.PreferenceScreen;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.widget.Toast;

import java.util.List;

import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.hisense.settings.util.Wrapper;

import android.util.Log;
import android.view.KeyEvent;

/**
 * Handles settings menu for 3D settings.  
 *
 * @author libaocheng
 */
public class ThreeDSettings extends SettingsPreferenceFragment implements
Preference.OnPreferenceChangeListener{
   
    private static final String TAG = "3D";

    private static final String KEY_THREED_MODE = "threed_mode";
    private static final String KEY_THREED_LR_SWITCH = "lr_switch";
//    private static final String KEY_THREED_VIEWPOINT = "threed_view_point";
//	private static final String KEY_THREED_FIELDDEPTH = "threed_field_depth";
	private static final String KEY_THREED_3DTO2D = "threed_to_twod";

    private static final int AUTO_MODE = 1;  //defined in SCMPQSettingsEnums.java
  
  	//Vivid 0
  	//Standard 1
  	//Theater 2
  	//Engery Savings 3
  	//Custom -1
	private static final int VALUE_DEFAULT_THREED_MODE = 0;
	private static final int VALUE_DEFAULT_LR_SWITCH = 0;
	
	//on 1
	//off 0
	private static final int VALUE_3DTO2D_ON = 1;
	private static final int VALUE_3DTO2D_OFF = 0;

	
    private ListPreference mThreeDModePreference;
	private ListPreference mThreeDLRSwitchPreference;
    private SeekBarDialogPreference mThreeDViewPointPreference;
	private SeekBarDialogPreference mThreeDFieldDepthPreference;
	private CheckBoxPreference m3Dto2DPreference;

	

/*
	private class IntPrefListener
		  implements Preference.OnPreferenceChangeListener {
	  private String mKey;

	  public IntPrefListener(String key) {
		  mKey = key;
	  }

	  public boolean onPreferenceChange(Preference preference,
			  Object newValue) {
		  String key = preference.getKey();
		  int value;
		  try {
			  value = Integer.parseInt((String) newValue);
		  } catch (NumberFormatException e) {
			  return false;
		  }
		  Settings.System.putInt(getContentResolver(), mKey,
				  value);
		  return true;
	  }
	}
*/
    @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.threed_settings);

		//3d mode
        mThreeDModePreference = (ListPreference) findPreference(KEY_THREED_MODE);
        final int currentThreeDMode = getThreeDMode();
        Log.d(TAG, "onCreate: getThreeDMode = " + getThreeDMode());
		updateThreeDModeTitle(currentThreeDMode);
		mThreeDModePreference.setOnPreferenceChangeListener(this);

		//3d lr switch
		mThreeDLRSwitchPreference = (ListPreference) findPreference(KEY_THREED_LR_SWITCH);
        final int currentThreeLRSwitch = getThreeDLRSwitch();
		updateThreeDLRSwitchTitle(currentThreeLRSwitch);
        mThreeDLRSwitchPreference.setOnPreferenceChangeListener(this);

		//view point
		mThreeDViewPointPreference = (SeekBarPreference)findPreference(KEY_THREED_VIEWPOINT);
		mThreeDViewPointPreference.setTitle(getString(R.string.threed_view_point).toString() + " : " + getThreeDViewPoint());
		mThreeDViewPointPreference.setOnPreferenceChangeListener(this);

		//field depth
		mThreeDFieldDepthPreference = (SeekBarPreference)findPreference(KEY_THREED_FIELDDEPTH);
		mThreeDFieldDepthPreference.setTitle(getString(R.string.threed_field_depth).toString() + " : " + getThreeDFieldDepth());
		mThreeDFieldDepthPreference.setOnPreferenceChangeListener(this);
        
        m3Dto2DPreference = (CheckBoxPreference)findPreference(KEY_THREED_3DTO2D);
        int current3Dto2D = get3Dto2DValue();
        m3Dto2DPreference.setOnPreferenceClickListener(
                new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = m3Dto2DPreference.isChecked();
                if (enabled) {
                    set3Dto2DValue(VALUE_3DTO2D_ON);
                } else {
                    set3Dto2DValue(VALUE_3DTO2D_OFF);
                }
                return true;
            }
        });
        

        mThreeDModePreference.setValue((String.valueOf(currentThreeDMode)));
		//updateThreeDModeSummary(currentThreeDMode);

		mThreeDLRSwitchPreference.setValue((String.valueOf(currentThreeLRSwitch)));
		//updateThreeDLRSwitchSummary(currentThreeLRSwitch);
		
		m3Dto2DPreference.setChecked(current3Dto2D != 0);
		
		setRelatedThreeDItemsState(currentThreeDMode);
		
//        setup3Dto2D();
    }

    private int getThreeDMode() {
        int threeDMode = Wrapper.getWrapperInstance().getInput3D();
        

        return threeDMode;
    }
    private void setThreeDMode(int threeDMode) {
        
		Wrapper.getWrapperInstance().setInput3D(threeDMode);
    }
	private int getThreeDLRSwitch() {
		
        int threeDLR = Wrapper.getWrapperInstance().getLRSwap();
        Log.d(TAG, "Get LR swith value is "+threeDLR);
        
        return threeDLR;
    }

	private void setThreeDLRSwitch(int threeDLR) {

		Wrapper.getWrapperInstance().setLRSwap(threeDLR);
    }

//	private int getThreeDFieldDepth() {
//		
//        int threeDFieldDepth = Wrapper.getWrapperInstance().getInput2Dto3DDepth();
//        
//        return threeDFieldDepth;
//    }
//
//	private void setThreeFieldDepth(int threeDFieldDepth) {
//
//		Wrapper.getWrapperInstance().setInput2Dto3DDepth(threeDFieldDepth);
//    }
//	private int getThreeDViewPoint() {
//		
//        int threeDViewPoint = Wrapper.getWrapperInstance().getInput2Dto3DAngle();
//        
//        return threeDViewPoint;
//    }
//
//	private void setThreeDViewPoint(int threeDViewPoint) {
//
//		Wrapper.getWrapperInstance().setInput2Dto3DAngle(threeDViewPoint);
//    }

    private int get3Dto2DValue() {

		int threeDto2D = Wrapper.getWrapperInstance().getInput3Dto2D();      
        return threeDto2D;
    }


    private void set3Dto2DValue(int threeDto2D) {

        Wrapper.getWrapperInstance().setInput3Dto2D(threeDto2D);
    }



    private void updateThreeDModeTitle(int value) {
    	if (value == AUTO_MODE) {  //Auto Mode, only show as title, not exist in the list.
    		mThreeDModePreference.setTitle(getString(R.string.threed_mode).toString() + " : " + getString(R.string.auto).toString());
    	} else {
    		mThreeDModePreference.setTitle(getString(R.string.threed_mode).toString() + " : "
    				+ getResources().getStringArray(R.array.threed_mode_entries)[mThreeDModePreference.findIndexOfValue(String.valueOf(value))]);	
    	}
	}

	private void updateThreeDLRSwitchTitle(int value) {
		mThreeDLRSwitchPreference.setTitle(getString(R.string.lr_switch).toString() + " : "
			+ getResources().getStringArray(R.array.lr_switch_entries)[mThreeDLRSwitchPreference.findIndexOfValue(String.valueOf(value))]);
	}
	
//    private void updateThreeDViewPointTitle(int value) {
//		mThreeDViewPointPreference.setTitle(getString(R.string.threed_view_point).toString() + " : " + getThreeDViewPoint());
//    }
//
//    private void updateThreeDFieldDepthTitle(int value) {
//		mThreeDFieldDepthPreference.setTitle(getString(R.string.threed_field_depth).toString() + " : " + getThreeDFieldDepth());
//    }

//    private void setup3Dto2D() {
//        final CheckBoxPreference pref =
//                (CheckBoxPreference) findPreference(KEY_THREED_3DTO2D);
//        pref.setPersistent(false);
//		
//		int value = get3Dto2DValue();
//        pref.setChecked(value != 0);
//        pref.setOnPreferenceClickListener(
//                new Preference.OnPreferenceClickListener() {
//            public boolean onPreferenceClick(Preference preference) {
//                boolean enabled = pref.isChecked();
//                if (enabled) {
//                    set3Dto2DValue(VALUE_3DTO2D_ON);
//                } else {
//                    set3Dto2DValue(VALUE_3DTO2D_OFF);
//                }
//                return true;
//            }
//        });
//    }
	
    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        return false;
    }

    public boolean onPreferenceChange(Preference preference, Object objValue) {
        final String key = preference.getKey();
        if (KEY_THREED_MODE.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
				setThreeDMode(value);
				updateThreeDModeTitle(value);
				setRelatedThreeDItemsState(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not 3D mode setting", e);
            }
        }
		else if (KEY_THREED_LR_SWITCH.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
				setThreeDLRSwitch(value);
				updateThreeDLRSwitchTitle(value);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not 3D LR setting", e);
            }
        }
//		else if (KEY_THREED_VIEWPOINT.equals(key)) {
//            int value = (Integer)objValue;
//            try {
//				setThreeDLRSwitch(value);
//				updateThreeDViewPointTitle(value);
//            } catch (NumberFormatException e) {
//                Log.e(TAG, "could not 3D ViewPoint setting", e);
//            }
//        }
//		else if (KEY_THREED_FIELDDEPTH.equals(key)) {
//            int value = (Integer)objValue;
//            try {
//				setThreeDLRSwitch(value);
//				updateThreeDFieldDepthTitle(value);
//            } catch (NumberFormatException e) {
//                Log.e(TAG, "could not 3D FieldDepth setting", e);
//            }
//        }

        return true;
    }
    
    public void setRelatedThreeDItemsState(int threeDMode){
		
       
	}
	
	
	
    private boolean isThreeDAutoMode(){

        return (getThreeDMode() == AUTO_MODE);
    }

    private static final int MESSAGE_FINISH = 1;
    private static final int MESSAGE_LRSWAP = 2;
    private static final int MESSAGE_3DTO2D = 3;
	
    private Handler mHandler = new Handler()
    {
        public void handleMessage(
                android.os.Message msg)
        {
            switch(msg.what){
            case MESSAGE_FINISH:
                super.handleMessage(msg);
                finish();     
                break;
            case MESSAGE_LRSWAP:
                Log.d(TAG, "reset LR swap.");
                int LRsvalue=getThreeDLRSwitch();
                setThreeDLRSwitch(LRsvalue);
                break;
            case MESSAGE_3DTO2D:
                Log.d(TAG, "reset 3Dto2D.");
                int Threedto2Dvalue=get3Dto2DValue();
                set3Dto2DValue(Threedto2Dvalue);
                break;
            default:
                break;
            }       
        };
    };
	
   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getScanCode() == 94)
        {
            mHandler.sendEmptyMessageDelayed(MESSAGE_FINISH, 200);
            return true;
        }
        else
            return super.onKeyDown(keyCode, event);
    }*/

/*
    //Auto 3D format will send "SCM_3DMODE_CHANGE" broadcast.

    public static class Auto3DModeReceiver extends BroadcastReceiver {

        public static final String EXTRA_USDTV_EVENT = "Events";

        @Override
        public void onReceive(Context context, Intent intent) {

            int event = intent.getIntExtra(EXTRA_USDTV_EVENT, 0);

            if (event == Events.SCM_3DMODE_CHANGE.ordinal()) {

                    //Toast.makeText(context, R.string.threed_wear_glasses_notice, Toast.LENGTH_LONG).show();
            }
        }
    }
*/   
}
